package mts.groupdispatcher;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

public class GroupDispatcherConnectionServer extends Thread {
	private static final Logger log = Logger.getLogger(GroupDispatcherConnectionServer.class);
	
	private ServerSocket serverSocket;
	private GroupDispatcher groupDispatcher;
	
	public GroupDispatcherConnectionServer(GroupDispatcher groupDispatcher, int serverPort) {
		this.groupDispatcher = groupDispatcher;
		try {
					
			serverSocket = new ServerSocket(serverPort);
		} catch (IOException ex) {
			log.error("Could not create Receive Server Socket.", ex);
			
			System.exit(1);
		}
	}
	
	private void receiveConnection() {
		
		while (true) {
			try {
				Socket clientSocket = serverSocket.accept();
				
				ElevatorControllerConnection elevatorControllerConnection = new ElevatorControllerConnection(groupDispatcher, clientSocket);
				elevatorControllerConnection.start();
				groupDispatcher.addElevatorController(elevatorControllerConnection);				
				
			} catch (IOException ex) {
				log.error("Error accepting connection from client.", ex);
			}				
		}				
	}		

	@Override
	public void run() {
		while (true) {
			receiveConnection();
		}
		
	}	
}
